package com.sbio.udiapp.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.blankj.utilcode.util.StringUtils;
import com.sbio.udiapp.R;
import com.sbio.udiapp.adapter.ListViewAdapter;
import com.sbio.udiapp.adapter.RawMaterialSubPackListViewAdapter;
import com.sbio.udiapp.cpcl.PrintUtil;
import com.sbio.udiapp.databinding.ActivityComparePriceBinding;
import com.sbio.udiapp.databinding.ActivityRawMaterialSubPackBinding;
import com.sbio.udiapp.di.ActivityManager;
import com.sbio.udiapp.listener.ListViewAdapterListener;
import com.sbio.udiapp.listener.RawMaterialSubPackListAdapterListener;
import com.sbio.udiapp.net.api.ApiService;
import com.sbio.udiapp.net.bean.AjaxResult;
import com.sbio.udiapp.ui.model.PrdMtrlView1;
import com.sbio.udiapp.ui.model.PrdMtrlView1;
import com.sbio.udiapp.ui.model.RawMaterialListItemView;
import com.sbio.udiapp.util.ApiServiceUtil;
import com.sbio.udiapp.util.DialogUtil;
import com.sbio.udiapp.util.SoundPlayerUtil;
import com.sbio.udiapp.util.StringUtil;
import com.sbio.udiapp.util.ToastUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@AndroidEntryPoint
public class RawMaterialSubPackActivity extends BaseBroadCastActivity {

    private ActivityRawMaterialSubPackBinding binding;

    @Inject
    ApiService apiService;

    ObservableList<PrdMtrlView1> dataList = new ObservableArrayList<>();

    RawMaterialSubPackListViewAdapter adapter;

    private int currentSelectedPosition = -1; // 初始没有选中项

    public int getCurrentSelectedPosition() {
        return currentSelectedPosition;
    }

    /**
     * 设置选中位置并更新UI
     */
    private void setSelectedPosition(int position) {
        int previousPosition = currentSelectedPosition;
        currentSelectedPosition = position;

        // 通知适配器更新前一个和当前选中项的UI
        if (previousPosition != -1) {
            adapter.notifyItemChanged(previousPosition);
        }
        adapter.notifyItemChanged(currentSelectedPosition);

        // 将选中项滚动到视口
        scrollToSelectedPosition(currentSelectedPosition);
    }

    /**
     * 滚动到选中位置
     */
    private void scrollToSelectedPosition(int position) {
        // 平滑滚动到选中项，使其显示在视口
        binding.dataListView.smoothScrollToPosition(position);

        // 如果你希望精确滚动到顶部，可以使用以下方法
        // layoutManager.scrollToPositionWithOffset(position, 20); // 20是顶部偏移量
    }

    @Override
    public void onBroadcastReceiver(String barcodeData) {

        if (barcodeData.startsWith("SOUT")) {
            binding.etBillNo.setText(barcodeData);
            ApiServiceUtil.enqueue(() -> apiService.getPrdMtrlView1(barcodeData), new Callback<AjaxResult>() {
                @Override
                public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                    hideProcess();
                    AjaxResult ajaxResult = response.body();
                    if (Objects.requireNonNull(ajaxResult).isSuccess()) {

                        List<PrdMtrlView1> views = ajaxResult.getDataListByClz(PrdMtrlView1.class);
                        dataList.clear();
                        dataList.addAll(views);
                        selectFirstItem();
                        ToastUtil.showSuccess("查询成功");
                    } else {
                        SoundPlayerUtil.playFail();
                        DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                    }
                }

                @Override
                public void onFailure(Call<AjaxResult> call, Throwable t) {
                    hideProcess();
                    DialogUtil.showErrorAlertDialog(t.getMessage());

                }
            });
        }

        if (barcodeData.startsWith("SS")) {
            String billNo = binding.etBillNo.getText().toString();
            if (StringUtils.isEmpty(billNo)) {
                ToastUtil.showLong("请先扫码生产领料单");
                return;
            }
            PrdMtrlView1 prdMtrlView1 = dataList.get(currentSelectedPosition);
            ApiServiceUtil.enqueue(() -> apiService.getRawMaterial(barcodeData, billNo, prdMtrlView1.getMoEntryId(), prdMtrlView1.getParentMaterialNo()), new Callback<AjaxResult>() {
                @Override
                public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                    hideProcess();
                    AjaxResult ajaxResult = response.body();
                    if (Objects.requireNonNull(ajaxResult).isSuccess()) {

                        RawMaterialListItemView view = ajaxResult.getDataByClz(RawMaterialListItemView.class);
                        if (Objects.equals(view.getOverControlMode(), "1") || StringUtils.isEmpty(view.getOverControlMode())) {
                            //最小发料批量
                            PrintUtil.printRawMaterial(view);
                            ToastUtil.showSuccess("打印成功");
                        } else if (Objects.equals(view.getOverControlMode(), "2")) {
                            confirmRawMaterialQty(view,prdMtrlView1.getParentMaterialNo());
                        }
                    } else {
                        SoundPlayerUtil.playFail();
                        DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                    }
                }

                @Override
                public void onFailure(Call<AjaxResult> call, Throwable t) {
                    hideProcess();
                    DialogUtil.showErrorAlertDialog(t.getMessage());

                }
            });
        }
    }


    public void confirmRawMaterialQty(RawMaterialListItemView datum,String parentMaterialNo) {


        Context context = ActivityManager.getCurrentActivity();

        // 加载自定义布局
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_custom_input, null);
        EditText etInput1 = view.findViewById(R.id.et_input1);
        etInput1.setHint("物料名称");
        etInput1.setText("物料名称："+datum.getMaterialName());
        etInput1.setEnabled(false);
        EditText etInput2 = view.findViewById(R.id.et_input2);
        etInput2.setHint("批号");
        etInput2.setText("批号："+datum.getLot());
        etInput2.setEnabled(false);
        EditText etInput3 = view.findViewById(R.id.et_input3);
        etInput3.setHint("数量");
        etInput3.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        etInput3.setText(datum.getQty().toString());

        // 构建 AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("确认修改原材料二维码并打印吗?")
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        BigDecimal input3 = null;
                        try {
                            input3 = new BigDecimal(etInput3.getText().toString());
                        } catch (NumberFormatException e) {
                            input3 = new BigDecimal("0");
                        }


                        BigDecimal finalInput3 = input3;
                        ApiServiceUtil.enqueue(() -> apiService.editPickMaterialQty(datum, binding.etBillNo.getText().toString(), finalInput3, parentMaterialNo), new Callback<AjaxResult>() {
                            @Override
                            public void onResponse(Call<AjaxResult> call, Response<AjaxResult> response) {
                                hideProcess();
                                AjaxResult ajaxResult = response.body();
                                if (Objects.requireNonNull(ajaxResult).isSuccess()) {

                                    PrintUtil.printRawMaterial4ReceiveBill(datum);

                                    ToastUtil.showSuccess("打印成功");
                                } else {
                                    SoundPlayerUtil.playFail();
                                    DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                                }
                            }

                            @Override
                            public void onFailure(Call<AjaxResult> call, Throwable t) {
                                hideProcess();
                                DialogUtil.showErrorAlertDialog(t.getMessage());
                            }
                        });
                    }
                })
                .setNegativeButton("取消", null)
                .show();


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRawMaterialSubPackBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initListViewListener();
        binding.btnPrev.setOnClickListener(v -> {
            selectPrevItem();
        });
        binding.btnNext.setOnClickListener(v -> {
            selectNextItem();
        });

        /*List<PrdMtrlView1> list = new ArrayList<>();
        IntStream.range(1, 20).forEach(it -> {
            PrdMtrlView1 prdMtrlView1 = new PrdMtrlView1();
            prdMtrlView1.setParentMaterialName("name" + it);
            prdMtrlView1.setSeq(1);
            prdMtrlView1.setParentMaterialNo("no" + it);
            list.add(prdMtrlView1);
        });
        dataList.addAll(list);*/
    }

    //初始化listView监听器
    private void initListViewListener() {
        //初始化nos listView布局
        binding.dataListView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RawMaterialSubPackListViewAdapter<>(dataList, this);
        adapter.setOnItemClickListener(position -> {
            setSelectedPosition(position);
        });
        binding.dataListView.setAdapter(adapter);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider)); // 设置自定义分割线样式
        binding.dataListView.addItemDecoration(dividerItemDecoration);
        binding.dataListView.setItemAnimator(new DefaultItemAnimator());


        dataList.addOnListChangedCallback(new ObservableList.OnListChangedCallback<ObservableList<PrdMtrlView1>>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onChanged(ObservableList<PrdMtrlView1> sender) {
                adapter.notifyDataSetChanged(); // 数据变化时通知适配器刷新列表
            }

            @Override
            public void onItemRangeChanged(ObservableList<PrdMtrlView1> sender, int positionStart, int itemCount) {
                adapter.notifyItemRangeChanged(positionStart, itemCount); // 通知适配器局部刷新
            }

            @Override
            public void onItemRangeInserted(ObservableList<PrdMtrlView1> sender, int positionStart, int itemCount) {
//                adapter.notifyItemRangeChanged(positionStart-1, itemCount); // 通知适配器局部刷新
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onItemRangeMoved(ObservableList<PrdMtrlView1> sender, int fromPosition, int toPosition, int itemCount) {
                adapter.notifyItemRangeRemoved(fromPosition, itemCount); // 通知适配器局部刷新
            }

            @Override
            public void onItemRangeRemoved(ObservableList<PrdMtrlView1> sender, int positionStart, int itemCount) {
                adapter.notifyItemRangeRemoved(positionStart, itemCount); // 通知适配器局部刷新
            }
        });
    }

    /**
     * 选中下一行
     */
    private void selectNextItem() {
        // 检查是否有下一项
        if (currentSelectedPosition < dataList.size() - 1) {
            // 计算下一项位置
            int nextPosition = currentSelectedPosition + 1;
            setSelectedPosition(nextPosition);
        }
    }

    /**
     * 选中上一行
     */
    private void selectPrevItem() {
        // 检查是否有上一项
        if (currentSelectedPosition > 0) {
            // 计算上一项位置
            int nextPosition = currentSelectedPosition - 1;
            setSelectedPosition(nextPosition);
        }
    }

    /**
     * 选中第一行
     */
    private void selectFirstItem() {
        if (currentSelectedPosition != 0) {
            setSelectedPosition(0);
        }
    }

}